import { Component } from '@angular/core';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';
import { Store } from '@ngxs/store';
import { LogisticsSelector } from '../store/logistics.selector';
import { LogisticsAction } from '../store/logistics.action';

@Component({
  selector: 'app-list',
  template: `
    <nz-table #basicTable [nzData]="(list$|async)||[]">
      <thead>
      <tr>
        <th nzWidth="200px">下单时间</th>
        <th nzWidth="200px">物流状态</th>
        <th nzWidth="200px">总价</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr *ngFor="let data of basicTable.data">
        <td>{{data.createTime|date:'yyyy-MM-dd HH:mm:ss'}}</td>
        <td>{{data.status|logisticsStatus}}</td>
        <td>{{totalPrice(data.data)}}</td>
        <td>
          <ng-container *ngIf="data.status === 1">
            <button nz-button nzSize="small" nzType="primary" (click)="mark(data,2)">标记出库</button>
            <nz-divider nzType="vertical"></nz-divider>
          </ng-container>
          <ng-container *ngIf="data.status === 2">
            <button nz-button nzSize="small" nzType="primary" (click)="mark(data,0)">标记到货</button>
            <nz-divider nzType="vertical"></nz-divider>
          </ng-container>
          <a (click)="delete(data)">删除</a>
        </td>
      </tr>
      </tbody>
    </nz-table>
  `,
  styles: [],
})
export class ListComponent {
  @AutoUnsubscribe() list$ = this.store.select(LogisticsSelector.list);

  constructor(private store: Store) {
  }

  totalPrice(data: any) {
    if (!data) return null;
    let totalPrice = 0;
    for (let datum of data) totalPrice += datum.count * datum.data.price;
    return totalPrice;
  }

  delete(data: any) {
    this.store.dispatch(new LogisticsAction.Delete(data));
  }

  mark(data: any, status: number) {
    this.store.dispatch(new LogisticsAction.Mark(data, status));
  }
}
